package com.ai.module.user.service.impl;

import com.ai.module.business.domain.vo.UserMessage;
import com.ai.module.business.enu.Source;
import com.ai.module.business.service.BannerRecordService;
import com.ai.module.business.service.MemberCenterService;
import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.ChatImagePointStringConstant;
import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.domain.vo.RiskReason;
import com.ai.module.chat.common.enu.MidJourneyParam;
import com.ai.module.chat.common.enu.ModelType;
import com.ai.module.chat.common.enu.StyleType;
import com.ai.module.chat.config.ChatImageBo;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.chat.config.properties.ChatGptProperty;
import com.ai.module.chat.util.DateUtils;
import com.ai.module.chat.util.MrHeOpenAiService;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.ai.module.chat.util.aliyun.AliyunUtil;
import com.ai.module.mj.constant.enums.TaskAction;
import com.ai.module.mj.constant.stringConstant.ReturnCode;
import com.ai.module.mj.domain.enu.ImageTaskSource;
import com.ai.module.mj.domain.req.SubmitBlendReq;
import com.ai.module.mj.domain.req.SubmitDescribeReq;
import com.ai.module.mj.domain.req.SubmitImagineReq;
import com.ai.module.mj.domain.req.SubmitSimpleChangeReq;
import com.ai.module.mj.domain.vo.SubmitResultVO;
import com.ai.module.mj.service.ImageSubmitService;
import com.ai.module.user.domain.bo.AiProductChat;
import com.ai.module.user.domain.entity.AIProductRecordEntity;
import com.ai.module.user.domain.entity.AiProductEntity;
import com.ai.module.user.domain.entity.PublicTitleEntity;
import com.ai.module.user.domain.enu.AIProductModelType;
import com.ai.module.user.domain.req.AiProductReq;
import com.ai.module.user.domain.req.ProductRecordReq;
import com.ai.module.user.domain.vo.*;
import com.ai.module.user.enu.AIType;
import com.ai.module.user.enu.PointSource;
import com.ai.module.user.mapper.AIProductRecordMapper;
import com.ai.module.user.mapper.AiProductMapper;
import com.ai.module.user.mapper.PublicPromptMapper;
import com.ai.module.user.mapper.PublicTitleMapper;
import com.ai.module.user.service.ChatService;
import com.ai.module.user.service.PublicTitleService;
import com.ai.module.user.service.UserImageAnalyzeService;
import com.ai.module.websocket.service.AIProductWebSocketService;
import com.ai.module.websocket.vo.WebSocketProduct;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import io.github.asleepyfish.service.OpenAiProxyService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.stream.Collectors;

import static com.ai.module.chat.common.constant.StringConstant.userROBOT;
import static com.ai.module.websocket.service.GlobalWebSocketService.userProductSessionMap;

/**
 * @author: heJinQin
 * @create: 2024-03-25 18:27
 * @description:
 **/
@Slf4j
@Service
public class PublicTitleServiceImpl extends ServiceImpl<PublicTitleMapper, PublicTitleEntity> implements PublicTitleService {

    @Autowired
    private PublicPromptMapper publicPromptMapper;

    @Autowired
    private AiProductMapper aiProductMapper;

    @Autowired
    private BannerRecordService bannerRecordService;

    @Autowired
    private OpenAiProxyService openAiProxyService;

    @Autowired
    private MrHeOpenAiService mrHeOpenAiService;

    @Autowired
    private AIProductRecordMapper aiProductRecordMapper;

    @Autowired
    private MemberCenterService memberCenter;

    @Autowired
    private ImageSubmitService submitService;

    @Autowired
    private ChatService chatService;

    @Autowired
    private UserImageAnalyzeService userImageAnalyzeService;
    @Autowired
    private ChatGptProperty chatGptProperty;
    @Autowired
    @Lazy
    private AIProductWebSocketService aiProductWebSocketService;

    @Override
    public List<PublicTitleVo> imagePrompt() {
        return this.baseMapper.imagePrompt();
    }

    @Override
    public List<AIProductVo> aiProduct(AIType aiType) {
        if (!RedisTemplateUtils.hasKey(RedisKeyStringConstant.AI_PRODUCT_Title)) {
            // 查询所有数据 封装成 map
            var aiProductVos = this.baseMapper.aiProduct(aiType);
            RedisTemplateUtils.set(RedisKeyStringConstant.AI_PRODUCT_Title, aiProductVos, DateUtils.TIME_DAY);
            return aiProductVos;
        }
        return RedisTemplateUtils.get(RedisKeyStringConstant.AI_PRODUCT_Title);
    }

    @Override
    public UserProductVo productChat(AiProductReq aiProductReq) {



        AiProductChat aiProductChat = getAiProductChat(aiProductReq);
        AIProductModelType modeType = aiProductChat.getModeType();
        aiProductReq.setModeType(modeType);
        UserProductVo userProductVo = checkUserQuestion(aiProductReq);
        if (userProductVo != null) {
            return userProductVo;
        }
        // 判断该数据是不是 过期了
        return getUserMessage(aiProductChat);
    }

    @NotNull
    private AiProductChat getAiProductChat(AiProductReq aiProductReq) {
        String businessId = aiProductReq.getRobotId();
        String message = aiProductReq.getMessage();
        if (!RedisTemplateUtils.hasKey(RedisKeyStringConstant.AI_PRODUCT)) {
            // 查询所有数据 封装成 map
            List<AiProductContent> allProductList = baseMapper.findAllProduct();
            allProductList.stream().forEach(t -> {
                RedisTemplateUtils.hset(RedisKeyStringConstant.AI_PRODUCT, t.getProductId(), t, DateUtils.TIME_DAY);
            });
        }
        AiProductChat aiProductChat = new AiProductChat();
        aiProductChat.setBusinessId(businessId);
        aiProductChat.setQuestion(message);
        aiProductChat.setUserFileUrl(aiProductReq.getImageUrlList());
        aiProductChat.setStream(aiProductReq.getStream());
        return aiProductChat;
    }

    @Nullable
    private UserProductVo checkUserQuestion(AiProductReq aiProductReq) {
        String askQuestion = aiProductReq.getMessage();
        String businessId = aiProductReq.getRobotId();
        AIProductModelType modeType = aiProductReq.getModeType();
        RiskReason riskReason = AliyunUtil.getRiskReason(askQuestion);
        Boolean success = riskReason.getSuccess();

        if (!success) {
            bannerRecordService.textCheck(String.join(",",
                            riskReason.getRiskWords()),
                    null,
                    askQuestion,
                    Source.USER_PROMPT
            );
            List<String> answerList = Collections.singletonList("提示词违反相关规则,多次将进行封号处理!!!");
            log.error("提示词违反相关规则,提示词为[{}],违反规则[{}]", askQuestion
                    , String.join(StringPool.COMMA, riskReason.getRiskTips()));
            AIProductRecordEntity aiProductRecord = new AIProductRecordEntity();
            aiProductRecord.setQuestion(askQuestion);
            aiProductRecord.setAnswer(JSONObject.toJSONString(answerList));
            aiProductRecord.setBusinessId(businessId);
            aiProductRecord.setUserId(ThreadLocalContext.getUserId());
            aiProductRecord.setCostTime(0L);
            aiProductRecord.setUserFile(null);
            if (modeType ==AIProductModelType.CHAT4_PIC ||
                modeType ==AIProductModelType.CHAT_3 ||
                modeType ==AIProductModelType.CHAT_4
            ){
                aiProductRecord.setAction(TaskAction.valueOf(String.valueOf(modeType)));
            }
            aiProductRecordMapper.insert(aiProductRecord);
            UserProductVo userProductVo = new UserProductVo();
            userProductVo.setAnswerList(Collections.singletonList("提示词违反相关规则,多次将进行封号处理!!!"));
            bannerRecordService.textCheck(String.join(",", riskReason.getRiskWords()),
                    aiProductRecord.getUuid(),
                    askQuestion,
                    Source.AI_PRODUCT_CHAT
            );
            return userProductVo;
//            throw new BusinessException("提示词违反相关规则,多次将进行封号处理!!!", ReturnCode.FAILURE);
        }
        return null;
    }

    private UserProductVo getUserMessage(AiProductChat aiProductChat) {
        checkUserPoints(aiProductChat);
        return doAiProductChatCommon(aiProductChat);
    }

    private void checkUserPoints(AiProductChat aiProductChat) {
        var robotId = aiProductChat.getBusinessId();
        boolean hHasKey = RedisTemplateUtils.hHasKey(RedisKeyStringConstant.AI_PRODUCT, robotId);
        if (!hHasKey) {
            AiProductEntity aiProductEntity = aiProductMapper.selectOne(
                    new LambdaQueryWrapper<AiProductEntity>()
                            .eq(AiProductEntity::getUuid, robotId));
            if (aiProductEntity == null) {
                throw new BusinessException("请刷新重试", ReturnCode.FAILURE);
            }
            AiProductContent aiProductContent = new AiProductContent();
            BeanUtils.copyProperties(aiProductEntity, aiProductContent);
            RedisTemplateUtils.hset(RedisKeyStringConstant.AI_PRODUCT, aiProductEntity.getUuid(), aiProductContent, DateUtils.WEK_DAY);
            // 开始对话
        }
        // 开始对话
        AiProductContent aiProduct = RedisTemplateUtils.hget(RedisKeyStringConstant.AI_PRODUCT, robotId);
        aiProductChat.setSystemValue(aiProduct.getSystemValue());
        checkUserPoint(aiProductChat, aiProduct);
    }

    private void checkUserPoint(AiProductChat aiProductChat, AiProductContent aiProduct) {
        AIProductModelType modelType = aiProduct.getModelType();
        aiProductChat.setModeType(modelType);
        // 校验用户积分
        // 区分模型
        switch (modelType) {
            case CHAT_3:
                memberCenter.checkChatPoint(ModelType.CHAT_3);
                break;
            case CHAT_4:
            case CHAT4_PIC:
                memberCenter.checkChatPoint(ModelType.CHAT_4);
                break;
            case MID_BLEND:
            case MID_DESC:
            case MID_IMAGE:
                memberCenter.checkUserPoints(ThreadLocalContext.getUserLoginInfo(), ChatImagePointStringConstant.fastCost);
                break;
//
//            case CHAT4_IMAGE:
//                log.info("这个是 chat4 多模型机器人呀 ~~~~~~");
//                break;
        }
    }

    public UserProductVo doAiProductChatCommon(AiProductChat aiProduct) {
        var askQuestion = aiProduct.getQuestion();
        var businessId = aiProduct.getBusinessId();
        // 校验 chat

        AIProductModelType modeType = aiProduct.getModeType();
        UserProductVo userProductVo = new UserProductVo();
        List<String> userFileUrl = aiProduct.getUserFileUrl();
        switch (modeType) {
            case CHAT_3:
            case CHAT_4:
            case CHAT4_PIC:
                if (!CollectionUtils.isEmpty(userFileUrl)
                        && modeType == AIProductModelType.CHAT4_PIC) {
                    return dealChat4Pic(aiProduct);
                } else {
                    List<String> answerList = dealRealChat34(aiProduct);
                    userProductVo.setAnswerList(answerList);
                    return userProductVo;
                }
            case MID_BLEND:
                SubmitBlendReq submitBlend = new SubmitBlendReq();
                if (CollectionUtils.isEmpty(userFileUrl)
                        && StringUtils.isBlank(askQuestion)
                ) {
                    throw new BusinessException("该机器人需要图片", ReturnCode.FAILURE);
                }
                if (CollectionUtils.isEmpty(userFileUrl)) {
                    var submitSimpleChangeReq = new SubmitSimpleChangeReq();
                    submitSimpleChangeReq.setContent(askQuestion);
                    SubmitResultVO imageR = submitService.simpleChange(submitSimpleChangeReq);
                    userProductVo.setTaskId(imageR.getTaskId());
                    break;
                }
                submitBlend.setTaskSource(ImageTaskSource.aiProduct);
                submitBlend.setFileUrlList(userFileUrl);
                submitBlend.setRobotId(businessId);
                SubmitResultVO blend = submitService.blend(submitBlend);
                userProductVo.setTaskId(blend.getTaskId());
                break;
            case MID_DESC:
                SubmitDescribeReq submitDesc = new SubmitDescribeReq();
                if (CollectionUtils.isEmpty(userFileUrl)
                        && StringUtils.isBlank(askQuestion)
                ) {
                    throw new BusinessException("该机器人需要图片", ReturnCode.FAILURE);
                }
                if (CollectionUtils.isEmpty(userFileUrl)) {
                    SubmitResultVO imageR = dealImage(aiProduct);
                    userProductVo.setTaskId(imageR.getTaskId());
                    break;
                }
                submitDesc.setFileUrlList(userFileUrl);
                submitDesc.setRobotId(businessId);
                submitDesc.setTaskSource(ImageTaskSource.aiProduct);
                SubmitResultVO describe = submitService.describe(submitDesc);
                userProductVo.setTaskId(describe.getTaskId());
                break;
            case MID_IMAGE:
            case MID_IMAGE_AI:

                SubmitResultVO imageR = dealImage(aiProduct);
                userProductVo.setTaskId(imageR.getTaskId());
                break;

        }

        return userProductVo;
    }

    private SubmitResultVO dealImage(AiProductChat aiProduct) {
        var askQuestion = aiProduct.getQuestion();
        var businessId = aiProduct.getBusinessId();
        // 校验 chat

        AIProductModelType modeType = aiProduct.getModeType();
        UserProductVo userProductVo = new UserProductVo();
        List<String> userFileUrl = aiProduct.getUserFileUrl();
        SubmitImagineReq submitImage = new SubmitImagineReq();
        submitImage.setTaskSource(ImageTaskSource.aiProduct);
        submitImage.setFileUrlList(userFileUrl);
        submitImage.setRobotId(businessId);
        submitImage.setPrompt(askQuestion);
        if (modeType==AIProductModelType.MID_IMAGE_AI){
            Map<MidJourneyParam, String> paramMap = new HashMap<>();
            paramMap.put(MidJourneyParam.CREF,"100");
            dealReplace(askQuestion, paramMap,MidJourneyParam.PICTURE_WEIGHT);
            dealReplace(askQuestion, paramMap,MidJourneyParam.STYLIZE);
            if (StringUtils.isNotBlank(askQuestion)
                    && !askQuestion.contains(StyleType.VIRTUALLY.getName()
                    .replace(" ",""))
            ){
                submitImage.setStyleType(StyleType.VIRTUALLY);
            }
            submitImage.setMidJourneyParams(paramMap);
            submitImage.setPrompt("转成动漫");
        }else {
            if (! CollectionUtils.isEmpty(userFileUrl)){
                Map<MidJourneyParam, String> paramMap = new HashMap<>();
                paramMap.put(MidJourneyParam.CREF,"0");
                dealReplace(askQuestion, paramMap,MidJourneyParam.STYLIZE);
                submitImage.setMidJourneyParams(paramMap);
            }
        }
        SubmitResultVO imageR = submitService.imagine(submitImage);
        return imageR;
    }

    private static void dealReplace(String askQuestion, Map<MidJourneyParam, String> paramMap,MidJourneyParam midJourneyParam) {
        if (org.springframework.util.StringUtils.hasText(askQuestion)
                && !askQuestion.contains(midJourneyParam.getValue().replace(" ",""))
        ){
            paramMap.put(midJourneyParam,"2");
        }
    }


    private UserProductVo dealChat4Pic(AiProductChat aiProduct) {
        String question = aiProduct.getQuestion();
        List<String> userFileUrl = aiProduct.getUserFileUrl();
        String fileUrl = userFileUrl.get(0);
        ChatImageBo.OpenaiContent openaiContent = new ChatImageBo.OpenaiContent();
        openaiContent.setType("text");
        openaiContent.setText(question);
        ArrayList<ChatImageBo.OpenaiContent> openaiContents = new ArrayList<>();
        openaiContents.add(openaiContent);

        ChatImageBo.OpenaiContent openaiImageContent = new ChatImageBo.OpenaiContent();
        openaiImageContent.setType("image_url");
        openaiImageContent.setImageUrl(new ChatImageBo.ImageUrl(
                fileUrl
        ));
        List<String> realContentList = userImageAnalyzeService
                .aIImageAnalyzeContent(question, openaiImageContent);
        UserProductVo userProductVo = new UserProductVo();
        userProductVo.setAnswerList(realContentList);
        // todo 多模态
        Boolean stream = aiProduct.getStream();
        if (stream) {
            String userUUID = ThreadLocalContext.getUserId();
            String robotId = aiProduct.getBusinessId();
            String userIdKey = String.format(userROBOT, userUUID, robotId);
            if (userProductSessionMap.containsKey(userIdKey)) {
                WebSocketSession webSocketSession = userProductSessionMap.get(userIdKey);
                WebSocketProduct webSocketProduct = new WebSocketProduct();
                WebSocketProduct.AiChat aiChat = new WebSocketProduct.AiChat();
                webSocketProduct.setAiChat(aiChat);
                aiChat.setEnd(true);
                aiChat.setAnswerList(realContentList);
                aiChat.setMessage(realContentList.get(0));
                aiProductWebSocketService.sendMessage(webSocketSession, webSocketProduct);
            }

        }
        dealUserPointChatDeduct(aiProduct,
                realContentList,
                ModelType.CHAT4_PIC);

        return userProductVo;
    }


    @NotNull
    private List<String> dealRealChat34(AiProductChat aiProduct) {
        var askQuestion = aiProduct.getQuestion();
        var system = aiProduct.getSystemValue();
        var start = aiProduct.getStart();
        var businessId = aiProduct.getBusinessId();
        UserLoginInfo userLoginInfo = ThreadLocalContext.getUserLoginInfo();
        var chatMessages = new ArrayList<ChatMessage>();
//        String content = "你现在是一个midJourney绘画提示词专家，专注于描述场景和人物的细节。请帮我生成一段关于详细描述关于'" + message + "'的绘画提示。结束时，请不要添加任何对画作影响或观者情感的期望描述。";
        ChatMessage systemMessage = new ChatMessage("system", system);
        ChatMessage chatMessage = new ChatMessage("user", askQuestion);
        chatMessages.add(systemMessage);
        chatMessages.add(chatMessage);
        Boolean stream = aiProduct.getStream();

        // 直接使用 websocket返回
        // 如果不是 webSocket 那就等待全部返回结束 在返回
        List<String> promptList = null;
        if (!stream) {
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model(chatGptProperty.getChatModel3())
                    .messages(chatMessages)
                    .user(ThreadLocalContext.getUserId() + StringPool.AT + DateUtils.getPaYear())
                    .temperature(1.0D)
                    .topP(1.0D)
                    .build();
            request.setMaxTokens(2000);
            promptList =
                    //Arrays.asList("loadCookie");
                    openAiProxyService.chatCompletion(request);
        } else {
            // 流处理
            UserTimeVo userTimeVo = getUserTimeVo(aiProduct,
                    promptList,
                    ModelType.CHAT_3,
                    null);
            mrHeOpenAiService.createStreamChatAIProductWebSocket(userTimeVo);
            String chatGptTalk = userTimeVo.getChatGptTalk();
            promptList = Collections.singletonList(chatGptTalk);
        }

        //this.save(userPrompt);
        dealUserPointChatDeduct(aiProduct, promptList, ModelType.CHAT_3);
        return promptList;
    }

    private void dealUserPointChatDeduct(
            AiProductChat aiProduct,
            List<String> promptList,
            ModelType modelType
    ) {
        String answer = promptList.get(0);
        var askQuestion = aiProduct.getQuestion();
        var start = aiProduct.getStart();
        var businessId = aiProduct.getBusinessId();
        AIProductModelType modeType = aiProduct.getModeType();
        UserMessage userMessage = new UserMessage();
        userMessage.setUserMessage(answer);
        // 进行记录入口
        AIProductRecordEntity aiProductRecord = new AIProductRecordEntity();
        aiProductRecord.setQuestion(askQuestion);
        aiProductRecord.setAnswer(JSONObject.toJSONString(promptList));
        aiProductRecord.setBusinessId(businessId);
        aiProductRecord.setUserId(ThreadLocalContext.getUserId());
        aiProductRecord.setCostTime(System.currentTimeMillis() - start);
        aiProductRecord.setUserFile(JSONObject.toJSONString(aiProduct.getUserFileUrl()));
        if (    modeType ==AIProductModelType.CHAT4_PIC ||
                modeType ==AIProductModelType.CHAT_3 ||
                modeType ==AIProductModelType.CHAT_4
        ){
            aiProductRecord.setAction(TaskAction.valueOf(String.valueOf(modeType)));
        }
        aiProductRecordMapper.insert(aiProductRecord);
        UserTimeVo userTimeVo = getUserTimeVo(aiProduct,
                promptList,
                modelType,
                aiProductRecord.getUuid());
        // 扣积分
        memberCenter.dealChatUserPoints(userTimeVo);
    }

    @NotNull
    private static UserTimeVo getUserTimeVo(AiProductChat aiProduct,
                                            List<String> promptList,
                                            ModelType modelType,
                                            String recordBusinessId) {
        UserLoginInfo userLoginInfo = ThreadLocalContext.getUserLoginInfo();

        var askQuestion = aiProduct.getQuestion();
        var start = aiProduct.getStart();
        var businessId = aiProduct.getBusinessId();
        UserTimeVo userTimeVo = new UserTimeVo();
        userTimeVo.setRobotId(aiProduct.getBusinessId());
        userTimeVo.setBeforePoints(userLoginInfo.getPoints());
        userTimeVo.setUuid(recordBusinessId);
        userTimeVo.setUser(userLoginInfo.getUuid());
        userTimeVo.setAskContent(askQuestion);
        userTimeVo.setChatGptTalk(JSONObject.toJSONString(promptList));
        userTimeVo.setIsVIP(userLoginInfo.getVip());
        userTimeVo.setSource(PointSource.product);
        userTimeVo.setSourceId(businessId);
        userTimeVo.setModelType(modelType);
        userTimeVo.setLoginToken(userLoginInfo.getLoginToken());
        return userTimeVo;
    }

    @Override
    public IPage<AiProductContentRecordVo> productRecord(ProductRecordReq productRecordReq) {
        String businessId = productRecordReq.getBusinessId();
        Page<AiProductContentRecordVo> aiProductContentRecordVoIPage = new Page<>(productRecordReq.getPage(), productRecordReq.getSize());
        return this.baseMapper.productRecord(aiProductContentRecordVoIPage, businessId, ThreadLocalContext.getUserId());
    }


    @Override
    public AiProductContent findAiProduct(String aiProductId) {
        var aiProduct = aiProductMapper.selectOne(
                new LambdaQueryWrapper<AiProductEntity>()
                        .eq(AiProductEntity::getUuid, aiProductId)

        );
        if (aiProduct == null) {
            throw new BusinessException("AI应用不存在", ReturnCode.FAILURE);
        }

        AiProductContent productContent = new AiProductContent();
        BeanUtils.copyProperties(aiProduct, productContent);
        productContent.setProductId(null);
        return productContent;
    }

    @Override
    public List<ImageMangeVo> imageMange() {
        boolean hasKey = RedisTemplateUtils.hasKey(RedisKeyStringConstant.AI_PRODUCT_ImageMange);
        if (!hasKey) {
            List<ImageMangeVo> imageMangeVos = baseMapper.imageMange();
            RedisTemplateUtils.set(RedisKeyStringConstant.AI_PRODUCT_ImageMange, imageMangeVos, DateUtils.TIME_DAY * 3);
            return imageMangeVos;
        }
        return RedisTemplateUtils.get(RedisKeyStringConstant.AI_PRODUCT_ImageMange);

    }


    @Override
    public AiProductContent aiImageProduct(AIProductModelType aiType) {
        if (!RedisTemplateUtils.hasKey(RedisKeyStringConstant.AI_PRODUCT_IMAGE)) {
            // 查询所有数据 封装成 map
//            List<AiProductContent> allProductList = baseMapper.findAllProduct();
            List<AiProductEntity> aiProductEntities = aiProductMapper.selectList(
                    new LambdaQueryWrapper<AiProductEntity>()
                            .eq(AiProductEntity::getModelType, aiType)
            );
            if (CollectionUtils.isEmpty(aiProductEntities)) {
                throw new BusinessException("AI产品已删");
            }
            AiProductEntity aiProductEntity = aiProductEntities.get(0);
            AiProductContent productContent = new AiProductContent();
            BeanUtils.copyProperties(aiProductEntity, productContent);
            return productContent;
        }
        return RedisTemplateUtils.get(RedisKeyStringConstant.AI_PRODUCT_IMAGE);
    }

    private static AiProductContent getAiProductContent(AIProductModelType aiType, List<AiProductContent> allProductList) {
        List<AiProductContent> collect = allProductList.stream().filter(t -> t.getModelType() == aiType).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            throw new BusinessException("AI产品已删");
        }
        return collect.get(0);
    }
}
